package com.aierkeji.call.cms.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.aierkeji.call.cms.entity.AkjCallRole;
import com.aierkeji.call.cms.entity.AkjCallUser;
import com.aierkeji.call.cms.util.StringUtils;


@Component
public class ShiroUserRealm extends AuthorizingRealm {

	

	/**授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法*/
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		//List<String> permissions=new ArrayList<String>();
//		Set<String> permissions=new HashSet<>();
//
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//
//		String account=(String) principals.getPrimaryPrincipal();
		AkjCallUser user = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
//		if(user==null) {
//			 user = akjAuserDao.findByAccount(account);
//		}
		if(user != null){
			List<AkjCallRole> roles =  user.getRoles();
			if(!CollectionUtils.isEmpty(roles)){
				roles.forEach(r ->{
					info.addRole(r.getCode());
				});
			}
//			info.addRoles(user.getRoles());


		}else {
			throw new AuthorizationException();
		}
		return info;
	}

	 /*** 认证回调函数，登录信息和用户验证信息验证*/
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		AkjCallUser user  = (AkjCallUser) token.getPrincipal();
		String password = new String((char[])token.getCredentials());
//		AkjAuser user = akjAuserDao.findByAccount(account);
        if(user == null) {
            throw new UnknownAccountException(); //如果用户名错误
        }
        if(!StringUtils.equals(password, user.getPwd())) {
            throw new IncorrectCredentialsException(); //如果密码错误
        }
//        如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(user.getAccount(), password, getName());
	}

}
